<!--
  描述：拖放地图组件，默认尺寸是 500 * 300

  接收属性参数：
    lat: 纬度
    lng: 经度

  自定义事件：
    drag: 拖放完成事件

  示例：
    <mapDrag @drag="dragMap" lat="22.574405" lng="114.095388"></mapDrag>
-->
<template>
  <div class="m-map">
    <div class="search" v-if="placeSearch">
      <input type="text" placeholder="请输入关键字" v-model="searchKey" />
      <button type="button" @click="handleSearch">搜索</button>
      <div id="js-result" v-show="searchKey" class="result"></div>
    </div>
    <div id="js-container" class="map">
      正在加载数据大约用时200ms,未加载成功请点击
      <span class="cursor" style="color: red" @click.stop="promisesAll"> 刷新 </span>
    </div>
  </div>
</template>

<script>
import remoteLoad from "@/utils/remoteLoad.js";
window._AMapSecurityConfig = {
  securityJsCode: "fce1eef68d233d9512366e99a74be3b3"
};
export default {
  props: ["lat", "lng"],
  inject: ["reload"],
  mounted() {
    this.promisesAll();
  },
  data() {
    return {
      searchKey: "",
      placeSearch: null,
      dragStatus: false,
      AMapUI: null,
      AMap: null,
      MapCityName: "青岛",
      MapKey: "ad0a36cf4602864c0c98b1bdcdf6dbcb"
    };
  },
  watch: {
    searchKey() {
      if (this.searchKey === "") {
        this.placeSearch.clear();
      }
    }
  },

  methods: {
    promisesAll() {
      setTimeout(() => {
        const one = new Promise((resolve, reject) => {
          const first = remoteLoad(`https://webapi.amap.com/maps?v=1.4.15&key=${this.MapKey}`);
          resolve(first);
        });
        const two = new Promise((resolve, reject) => {
          const second = remoteLoad("https://webapi.amap.com/ui/1.0/main.js");
          resolve(second);
        });
        Promise.all([one, two]).then(() => this.initMap());
      }, 1000);
    },
    // 搜索
    handleSearch() {
      if (this.searchKey) {
        this.placeSearch.search(this.searchKey);
      }
    },
    // 实例化地图
    initMap() {
      // 加载PositionPicker，loadUI的路径参数为模块名中 'ui/' 之后的部分
      const AMapUI = (this.AMapUI = window.AMapUI);
      const AMap = (this.AMap = window.AMap);
      // AMap.getCurrentPosition(function(status, result) {
      // });

      AMapUI.loadUI(["misc/PositionPicker"], (PositionPicker) => {
        const mapConfig = {
          zoom: 16
          // cityName: this.MapCityName
        };
        AMap.plugin("AMap.Geolocation", function () {
          var geolocation = new AMap.Geolocation({
            GeoLocationFirst: true,
            enableHighAccuracy: true
          });
          geolocation.getCurrentPosition(function (status, result) {
            if (status !== "complete") return;
            if (result.position.lat && result.position.lng) {
              mapConfig.center = [result.position.lng, result.position.lat];
            }
          });
        });
        // if (this.lat && this.lng) {
        // mapConfig.center = [this.lng, this.lat];
        // }
        const map = new AMap.Map("js-container", mapConfig);
        // 加载地图搜索插件
        AMap.service("AMap.PlaceSearch", () => {
          this.placeSearch = new AMap.PlaceSearch({
            pageSize: 5,
            pageIndex: 1,
            // citylimit: true,
            // city: this.MapCityName,
            map: map,
            panel: "js-result"
          });
        });
        // 启用工具条
        AMap.plugin(["AMap.ToolBar"], function () {
          map.addControl(
            new AMap.ToolBar({
              position: "RB"
            })
          );
        });
        // 创建地图拖拽
        const positionPicker = new PositionPicker({
          mode: "dragMap", // 设定为拖拽地图模式，可选'dragMap'、'dragMarker'，默认为'dragMap'
          map: map // 依赖地图对象
        });
        // 拖拽完成发送自定义 drag 事件
        positionPicker.on("success", (positionResult) => {
          // 过滤掉初始化地图后的第一次默认拖放
          if (!this.dragStatus) {
            this.dragStatus = true;
          } else {
            this.$emit("drag", positionResult);
          }
        });
        // 启动拖放
        positionPicker.start();
      });
    }
  },
  async created() {
    // 已载入高德地图API，则直接初始化地图
    if (window.AMap && window.AMapUI) {
      this.initMap();
      // 未载入高德地图API，则先载入API再初始化
    } else {
      await remoteLoad(`https://webapi.amap.com/maps?v=1.4.15&key=${this.MapKey}`);
      await remoteLoad("https://webapi.amap.com/ui/1.0/main.js");
      this.initMap();
    }
  }
};
</script>

<style lang="css">
.m-map {
  min-width: 500px;
  min-height: 400px;
  position: relative;
}
.m-map .map {
  min-width: 500px;
  min-height: 400px;
}
.m-map .search {
  position: absolute;
  top: 10px;
  left: 10px;
  width: 285px;
  height: 300px;
  z-index: 1;
}
.m-map .search input {
  width: 180px;
  border: 1px solid #ccc;
  line-height: 20px;
  padding: 5px;
  outline: none;
}
.m-map .search button {
  line-height: 26px;
  background: #fff;
  border: 1px solid #ccc;
  width: 50px;
  text-align: center;
}
.m-map .result {
  max-height: 300px;
  overflow: auto;
  margin-top: 10px;
}
</style>
